# -*- coding: utf-8 -*-
import requests
import os
from config import proxy

dirName = 'images'
_proxy = requests.get(proxy).text
proxies = {
  'http': 'http://' + _proxy
}
# 下载图片
def download(picPath,src, id):
  if not os.path.isdir(dirName + '/' + picPath + '_' + str(id)):
      os.mkdir(dirName + '/' + picPath + '_' + str(id))
      print(dirName + '/' + picPath + '_' + str(id) + "文件夹创建成功")
  dir = dirName + '/' + picPath + '_' + str(id) + '/' + str(id) + '.webp'
  imageHeader  = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    #'accept-encoding': 'gzip, deflate',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'max-age=0',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
  }
  try:
    pic = requests.get(src,headers=imageHeader,timeout=50,proxies=proxies)
    fp = open(dir, 'wb')
    fp.write(pic.content)
    fp.close()
    print(src, "下载成功！")
  except requests.exceptions.ConnectionError:
    print('Sorrry,image cannot downloaded, url is error{}.'.format(src))
